<?php
namespace app\admin\controller;

use think\Facade\Db;

class Login extends Common
{
    public function index()
    {
        return view();
    }

    public function login(){
        $dataArr = $this->request->request('user/a', []);

        if(!$dataArr['username'])  return json(array('result'=>'fail', 'title'=>lang('userLogin.username')));
        if(!$dataArr['password'])  return json(array('result'=>'fail', 'title'=>lang('userLogin.password')));

        $resList = Db::name('user')->field('password, id, status, admintype, rid, cid')->where(['username'=>$dataArr['username'], 'is_delete'=>1])->find();

        if($resList){
            if($resList['status'] == 2)  return json(array('result'=>'fail', 'title'=>lang('userLogin.userProhibit')));

            //查询该用户所属角色是否被禁用
            $roleInfo = Db::name('role')->field('name, status, examine_num')->where(['id'=>$resList['rid'] , 'is_delete'=>1])->find();
            if(!$roleInfo)  return json(array('result'=>'fail', 'title'=>lang('userLogin.roleDel')));
            if($roleInfo['status'] == 2)  return json(array('result'=>'fail', 'title'=>lang('userLogin.roleProhibit')));

            $newPas = md5(md5($dataArr['password']));
            if($resList['password'] == $newPas){
                //登陆成功...
                session('adminUserInfo', ['username'=>$dataArr['username'], 'uid'=>$resList['id'], 'admintype'=>$resList['admintype'], 'rid'=>$resList['rid'], 'cid'=>$resList['cid'], 'rolename'=>$roleInfo['name'], 'role_examine_num'=>$roleInfo['examine_num']]);

                event('UserLogin');
                $url = url('index/index');
                return json(array('result'=>'success', 'url'=>(string)$url, 'title'=>lang('userLogin.loginSucess')));
            }else{
                return json(array('result'=>'fail', 'title'=>lang('userLogin.passError')));
            }
        }else{
            return json(array('result'=>'fail', 'title'=>lang('userLogin.userNotExist')));
        }
    }

    public function loginOut(){
        session(null);
        return redirect((string)url('Login/index'));
    }
}
